package daily.may0516;

import java.util.ArrayList;
import java.util.Collections;

class Student implements Comparable {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + ":" + age;
    }

    //重写Comparable接口的compareTo方法
    @Override
    public int compareTo(Object o) {
        //多态：向下转型
        Student stu = (Student) o;
        //定义比较方式，先比较age
        if (this.age > stu.age) {
            return 1;//返回1为升序，返回-1为降序
        }
        //年龄相同则比较name
        if (0 == this.age - stu.age) {
            //这里调用的是String类的compareTo方法，默认为首字母升序。
            //不要与此处重写的compareTo方法混淆。
            return this.name.compareTo(stu.name);
        }
        return -1;
    }
}

public class SortTest {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("张三", 22));
        list.add(new Student("李四", 19));
        list.add(new Student("王五", 19));
        list.add(new Student("赵六", 21));
        list.add(new Student("田七", 20));
        list.add(new Student("田七", 18));//同名不同龄
        list.add(new Student("赵六", 21));//重复
        //通过实现Comparable接口，调用sort方法升序排序
        Collections.sort(list);
        System.out.println(list);
    }
}
//输出结果：
//[田七:18, 李四:19, 王五:19, 田七:20, 赵六:21, 张三:22]